package com.bestcem.xm.qdes.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bestcem.xm.component.mybatis.service.impl.XmServiceImpl;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.qdes.controller.param.UpdateQdesTagrefParam;
import com.bestcem.xm.qdes.entity.QdesTagRef;
import com.bestcem.xm.qdes.grpc.v1.services.TagRefRefType;
import com.bestcem.xm.qdes.mapper.QdesTagRefMapper;
import com.bestcem.xm.qdes.service.QdesTagRefService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class QdesTagRefServiceImpl extends XmServiceImpl<QdesTagRefMapper, QdesTagRef> implements QdesTagRefService {

    @Override
    public List<QdesTagRef> getQdesTagref(String id) {
        LambdaQueryWrapper<QdesTagRef> wrapper = new LambdaQueryWrapper();
        wrapper.eq(QdesTagRef::getRefId, id);
        return baseMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQdesTagref(String id, List<UpdateQdesTagrefParam.TagData> labels) {
        //删除原有关联记录
        LambdaQueryWrapper<QdesTagRef> wrapper = new LambdaQueryWrapper();
        wrapper.eq(QdesTagRef::getRefId, id);
        //此处为物理删除，因为表中有唯一联合键
        baseMapper.delete(wrapper);
        //创建新的关联记录
        if (CollUtil.isNotEmpty(labels)) {
            String orgId = SecurityContextHolder.getOrgId();
            String userId = SecurityContextHolder.getUserId();
            List<QdesTagRef> list = new ArrayList<>(labels.size());
            //设置公共字段属性
            QdesTagRef qdesTagref = new QdesTagRef();
            qdesTagref.setRefType(TagRefRefType.TAGREF_REF_TYPE_PROJECT.getNumber());
            qdesTagref.setProjectId(id);
            qdesTagref.setRefId(id);
            qdesTagref.setCompanyId(orgId);
            qdesTagref.setCreator(userId);
            qdesTagref.setCreatedId(userId);
            qdesTagref.setUpdatedId(userId);
            //开始遍历
            labels.forEach(v -> {
                QdesTagRef tagref = new QdesTagRef();
                BeanUtil.copyProperties(qdesTagref, tagref);
                tagref.setTagId(v.getTagId());
                tagref.setTagTitle(v.getTagTitle());
                list.add(tagref);
            });
            if (CollUtil.isNotEmpty(list)) {
                //批量创建
                baseMapper.insertBatchSomeColumn(list);
            }
        }
    }
}
